package tv.acgn.advertisement.servicebase.advice;

import java.io.IOException;
import java.lang.reflect.Type;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import tv.acgn.advertisement.servicebase.service.RequestCheckReplayService;

/**
 * @author : junG
 * @program : advertisement-ad-servicebase-advice
 * @description : 调用请求统一拦截器
 * 网络请求前置处理
 *
 * 工作流程在将请求的主体读取和转换成一个对象之前对请求进行自定义，
 * 并允许在将其传递到控制器方法作为一个@RequestBody或HttpEntity方法参数之前处理结果对象。
 * @date : 2019-06-01 19:15
 **/
@Slf4j
@ControllerAdvice
public class CommonRequestDataAdvice implements RequestBodyAdvice {

    @Autowired
    private RequestCheckReplayService checkReplayService;
    private HttpInputMessage inputMessage;
    private MethodParameter parameter;
    private Type targetType;
    private Class<? extends HttpMessageConverter<?>> converterType;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {

        return false;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        this.inputMessage = inputMessage;
        this.parameter = parameter;
        this.targetType = targetType;
        this.converterType = converterType;
        checkReplayService.checkRequest(inputMessage);

        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {
        return null;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
        Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return null;
    }
}
